/**
 * 
 */
package com.pengtu.web.detect;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.pengtu.dao.QueryFilter;
import com.pengtu.entity.detect.grade.Branch;
import com.pengtu.entity.detect.grade.Projquacheck;
import com.pengtu.entity.detect.grade.SignGradeVO;
import com.pengtu.entity.detect.grade.SignProjQuaCheck;
import com.pengtu.entity.detect.grade.Subentry;
import com.pengtu.entity.detect.grade.UnitProj;
import com.pengtu.entity.project.ProjectInfo;
import com.pengtu.entity.project.SignUpContract;
import com.pengtu.service.detect.ProjquacheckManager;
import com.pengtu.service.project.ProjectManager;
import com.pengtu.utils.MathsUtils;
import com.pengtu.utils.web.Struts2Utils;

/**
 * @author Administrator
 * 
 */
@Namespace("/detect/grade")
public class SignprojquaAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private ProjquacheckManager projquacheckManager;
	private ProjectManager projectManager;
	private String id;
	private String[] entryIdArr = {};
	private List<SignGradeVO> signGrades = new ArrayList<SignGradeVO>();
	private List<SignUpContract> conSignList;

	@Override
	public String input() throws Exception {
		SignProjQuaCheck signProjQua;
		// TODO Auto-generated method stub
		if (StringUtils.isEmpty(id)) {
			signProjQua = new SignProjQuaCheck();
			// 获得抽查项目
			// 构造单位工程集合
			List<UnitProj> unitProjList = new ArrayList<UnitProj>();
			// 声明抽查项目的集合
			List<Projquacheck> checkProjList = new ArrayList<Projquacheck>();

			for (int i = 0; i < entryIdArr.length; i++) {
				if (StringUtils.isNotEmpty(entryIdArr[i])) {
					Projquacheck projqua = projquacheckManager.findByProperty(
							"id", entryIdArr[i]);
					checkProjList.add(projqua);
				}
			}
			// 遍历选择项
			UnitProj unitProj = new UnitProj();
			Branch branch = new Branch();
			List<Subentry> oldSubList = new ArrayList<Subentry>();
			for (int i = 0; i < checkProjList.size(); i++) {

				// 标记当前单位工程
				String unitProjCode = "";
				// 标记当前分部
				String branchCode = "";
				// 获取前一位的单位与分部编码
				unitProjCode = unitProj.getUnitProjCode();
				branchCode = branch.getBranchCode();
				if (!checkProjList.get(i).getUnitProjCode()
						.equals(unitProjCode)) {
					unitProj = new UnitProj();
					unitProj.setUnitProjName(checkProjList.get(i).getUnitProj());
					unitProj.setUnitProjCode(checkProjList.get(i)
							.getUnitProjCode());
					unitProjList.add(unitProj);
				}
				if (!checkProjList.get(i).getBranchProjCode()
						.equals(branchCode)) {

					branch = new Branch();
					branch.setBranchName(checkProjList.get(i)
							.getBranchProjType());
					branch.setBranchCode(checkProjList.get(i)
							.getBranchProjCode());
					branch.setBranchValue(checkProjList.get(i)
							.getBranchProjValue());
					unitProj.addBranch(branch);

				}
				Subentry subentry = new Subentry();
				subentry.setSubentryName(checkProjList.get(i)
						.getCheckProjName());
				subentry.setSubentryCode(checkProjList.get(i)
						.getCheckProjCode());
				subentry.setSubentryValue(checkProjList.get(i)
						.getCheckProjValue());

				// 判断是否为修改
				// String subCodeString =
				// Struts2Utils.getParameter("subCodeString");
				String singcheckId = Struts2Utils.getParameter("singcheckId");

				// 查找修改的鉴定合同段
				// SignProjQuaCheck signcheck =
				// projquacheckManager.findByProjSign("id", singcheckId);
				// 已经检查项集合
				if (StringUtils.isNotEmpty(singcheckId)) {
					// 加去掉返回标记
					Struts2Utils.getRequest().setAttribute("backtab", true);
					oldSubList = projquacheckManager
							.findByHqlSigncheck(singcheckId);

					// String [] subCodeArr = subCodeString.split(",");
					boolean tab = true;
					if (oldSubList.contains(subentry)) {
						for (int k = 0; k < oldSubList.size(); k++) {
							Subentry oldSub = oldSubList.get(k);
							if (subentry.getSubentryCode().equals(
									oldSub.getSubentryCode())) {

								// 将已检查的数据复制到新集合的相同检查项中
								subentry.setCheckTotal(oldSub.getCheckTotal());
								subentry.setQualifiedTotal(oldSub
										.getQualifiedTotal());

								// 复制数据到同分部中
								Branch oldBranch = oldSub.getBranch();
								branch.setBranchPoint(null);
								branch.setFacadePoint(oldBranch
										.getFacadePoint());
								branch.setProjPart(oldBranch.getProjPart());
								branch.setQuaLevel(null);
								// 复制数据到同单位工程中

								UnitProj oldUnitProj = oldBranch.getUnitProj();
								unitProj.setPathName(oldUnitProj.getPathName());
								unitProj.setQuaLevel(null);
								unitProj.setUnitProjPoint(null);
								unitProj.setUnitProjPrice(oldUnitProj
										.getUnitProjPrice());
								unitProj.setWorkArea(oldUnitProj.getWorkArea());

								if (tab) {
									SignProjQuaCheck signcheckk = oldUnitProj
											.getSignQuaCheck();
									signProjQua.setInnerSheetPoint(signcheckk
											.getInnerSheetPoint());
									signProjQua.setSignProjPrice(signcheckk
											.getSignProjPrice());
									signProjQua.setSignContruct(oldUnitProj
											.getSignQuaCheck()
											.getSignContruct());
									tab = false;
								}
								oldSubList.remove(oldSub);
							}
						}
					}
				}

				branch.addSubentry(subentry);
			}
			if (oldSubList.size() > 0) {
				for (Subentry delesub : oldSubList) {
					projquacheckManager.deleteSub(delesub);
				}
			}
			signProjQua.setUnitProjList(unitProjList);
			SignUpContract signup = new SignUpContract();
			String signId = Struts2Utils.getParameter("signId");
			if (StringUtils.isNotEmpty(signId)) {
				signup.setId(signId);
				signProjQua.setSignContruct(signup);
			}
			Struts2Utils.getSession().setAttribute("signProjQuaCheck",
					signProjQua);
			signProjQua.setProjId(Struts2Utils.getParameter("projectId"));

		} else {
			signProjQua = projquacheckManager.findByProjSign("id", id);
			Struts2Utils.getSession().setAttribute("signProjQuaCheck",
					signProjQua);
		}
		return INPUT;
	}

	public String save() throws Exception {
		// 获得单位工程集合
		SignProjQuaCheck signProjQuaCheck = (SignProjQuaCheck) Struts2Utils
				.getSession().getAttribute("signProjQuaCheck");
		if (null != signProjQuaCheck) {
			List<UnitProj> unitList = signProjQuaCheck.getUnitProjList();
			Struts2Utils.getSession().removeAttribute("signProjQuaCheck");
			if (unitList.size() > 0) {
				for (int i = 0; i < unitList.size(); i++) {
					// 根据单位工程Code，获得对应的页面属性值
					UnitProj unpj = unitList.get(i);
					String unitProjMark = unpj.getUnitProjCode();
					if (StringUtils.isNotEmpty(Struts2Utils
							.getParameter("unitProjId_" + unitProjMark))) {
						unpj.setId(Struts2Utils.getParameter("unitProjId_"
								+ unitProjMark));
					}
					if (StringUtils.isNotEmpty(id)) {
						SignProjQuaCheck signproj = new SignProjQuaCheck();
						signproj.setId(id);
						unpj.setSignQuaCheck(signproj);
					}
					unpj.setPathName(Struts2Utils.getParameter("pathName_"
							+ unitProjMark));
					unpj.setQuaLevel(Struts2Utils.getParameter("quaLevel_"
							+ unitProjMark));
					unpj.setUnitProjPoint(new Double(Struts2Utils
							.getParameter("unitProjPoint_" + unitProjMark)));
					unpj.setUnitProjPrice(new Double(Struts2Utils
							.getParameter("unitProjPrice_" + unitProjMark)));
					unpj.setWorkArea(Struts2Utils.getParameter("workArea_"
							+ unitProjMark));
					// 获得分部工程集合
					List<Branch> branList = unpj.getBranchList();
					for (int j = 0; j < branList.size(); j++) {
						// 根据分部Code,获得对应的页面属性值
						String branMark = branList.get(j).getBranchCode();
						branList.get(j).setBranchPoint(
								new Double(
										Struts2Utils
												.getParameter("branchPoint_"
														+ branMark)));
						branList.get(j)
								.setCheckPoint(
										new Double(Struts2Utils
												.getParameter("checkPoint_"
														+ branMark)));
						branList.get(j).setFacadePoint(
								new Double(
										Struts2Utils
												.getParameter("facadePoint_"
														+ branMark)));
						branList.get(j).setId(
								Struts2Utils.getParameter("branchId_"
										+ branMark));
						branList.get(j).setProjPart(
								Struts2Utils.getParameter("projPart_"
										+ branMark));
						branList.get(j).setQuaLevel(
								Struts2Utils.getParameter("quaLevel_"
										+ branMark));

						// 获得抽查项目的集合
						List<Subentry> subList = branList.get(j)
								.getSubentryList();
						for (int k = 0; k < subList.size(); k++) {
							// 根据抽查项目COde,获取对应的页面属性值
							String subeMark = subList.get(k).getSubentryCode();
							subList.get(k).setCheckTotal(
									Integer.parseInt(Struts2Utils
											.getParameter("checkTotal_"
													+ subeMark)));
							subList.get(k).setId(
									Struts2Utils.getParameter("subentryId_"
											+ subeMark));
							subList.get(k).setQualifiedTotal(
									Integer.parseInt(Struts2Utils
											.getParameter("qualifiedTotal_"
													+ subeMark)));
							projquacheckManager.saveSubentry(subList.get(k));
						}
						branList.get(j).setSubentryList(subList);
						// branList.get(j).setUnitProj(unpj);
						projquacheckManager.saveProjBranch(branList.get(j));
					}
					unpj.setBranchList(branList);
					projquacheckManager.saveUnitProj(unpj);
				}
				signProjQuaCheck.setUnitProjList(unitList);
			}
			signProjQuaCheck.setSignProjPrice(new Double(Struts2Utils
					.getParameter("signProjPrice")));
			signProjQuaCheck.setQuaLevel(Struts2Utils.getParameter("quaLevel"));
			signProjQuaCheck.setCheckPoint(new Double(Struts2Utils
					.getParameter("checkPoint")));
			signProjQuaCheck.setInnerSheetPoint(new Double(Struts2Utils
					.getParameter("innerSheetPoint")));
			signProjQuaCheck.setAppraisalPoint(new Double(Struts2Utils
					.getParameter("appraisalPoint")));
			SignUpContract signup = new SignUpContract();
			String signId = Struts2Utils.getParameter("signId");
			if (StringUtils.isNotEmpty(signId)) {
				signup.setId(signId);
				signProjQuaCheck.setSignContruct(signup);
			}
			signProjQuaCheck.setProjId(Struts2Utils.getParameter("projectId"));
			projquacheckManager.saveProjSign(signProjQuaCheck);

			id = signProjQuaCheck.getId();
			Struts2Utils
					.sendRedirectUrl("/detect/grade/signprojqua!projconsignlist.action"
							+ "?projectId=" + signProjQuaCheck.getProjId());
		}
		return NONE;
	}

	public void fingProjSign() {
		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		String projectId = Struts2Utils.getParameter("projectId");
		queryfilter.addFilter("projectId", projectId);
		queryfilter.addFilter("contractKind", "4");
		conSignList = projectManager.findPageSign(queryfilter);
		ProjectInfo project = projectManager.getProj("id", projectId);
		Struts2Utils.getRequest().setAttribute("proj", project);
		// 建设项目评分值
		Double pointValue;
		// 合同段积分和
		Double signprojPoint = new Double(0);
		// 合同段投资额总和
		Double signprojPrice = new Double(0);
		// 建设项目单位工程优良率
		String fineProper;
		Double finePro;
		int fineNum = 0;
		// 建设项目工程质量等级
		String level;
		boolean belowSta = true;

		if (conSignList.size() > 0) {
			for (int i = 0; i < conSignList.size(); i++) {
				SignUpContract signUpContract = conSignList.get(i);
				// 获得与当前施工合同段对应的鉴定合同段
				SignProjQuaCheck signproj = projquacheckManager.findByProjSign(
						"signContruct.id", signUpContract.getId());
				// 将施工合同段与对应的鉴定合同段存入VO中
				SignGradeVO signGradeVO = new SignGradeVO();
				signGradeVO.setSignUpContract(signUpContract);
				// 如果没有评定,则不加入VO中
				if (null != signproj) {
					signGradeVO.setSignProjQuaCheck(signproj);
					// 累加建设项目的加权得分
					signprojPoint += signproj.getAppraisalPoint()
							* signproj.getSignProjPrice();
					// 累加建设项目的投资额
					signprojPrice += signproj.getSignProjPrice();
					// 累计建设项目下的评级为'优良'的单位工程数
					if (signproj.getQuaLevel().equals("优良")) {
						fineNum++;
					}
					// 标记建设项目中是否有评分'不合格'的鉴定合同段
					if (signproj.getQuaLevel().equals("不合格") && belowSta) {
						belowSta = false;
					}
				}
				signGrades.add(signGradeVO);
			}
			// 计算建设项目单位工程优良率
			finePro = MathsUtils.div("2", fineNum, signGrades.size());
			// 拼接表达式
			fineProper = fineNum + "/" + signGrades.size() + "=" + finePro
					* 100 + "%";
			Struts2Utils.getRequest().setAttribute("fineProper", fineProper);

			if (signprojPrice != 0) {
				// 建设项目工程质量（加权）评分值
				pointValue = MathsUtils.div("2", signprojPoint, signprojPrice);
				Struts2Utils.getRequest()
						.setAttribute("pointValue", pointValue);
				// 如果建设项目下所有鉴定合同段的评级均合格,按评级评出建设项目质量等级
				if (belowSta) {
					if (pointValue - 90 >= 0) {
						level = "优良";
					} else if (pointValue - 75 > 0) {
						level = "合格";
					} else {
						level = "不合格";
					}
				} else {
					level = "不合格";
				}
				Struts2Utils.getRequest().setAttribute("signprojPoint",
						signprojPoint);
				Struts2Utils.getRequest().setAttribute("signprojPrice",
						signprojPrice);
				Struts2Utils.getRequest().setAttribute("level", level);
			}
		}
	}

	@Action("/detect/grade/signprojqua")
	public String projconsignlist() {
		fingProjSign();
		return "signcon";
	}

	public String showProj() {

		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		String projectId = Struts2Utils.getParameter("projectId");
		queryfilter.addFilter("projectId", projectId);
		queryfilter.addFilter("contractKind", "4");
		// 获得当前工程下所有施工合同段
		conSignList = projectManager.findPageSign(queryfilter);
		if (StringUtils.isNotEmpty(projectId)) {
			ProjectInfo project = projectManager.getProj("id", projectId);
			Struts2Utils.getRequest().setAttribute("proj", project);
		}

		if (conSignList.size() > 0) {

			// 汇总单位工程下所有的抽查项目
			List<Subentry> fineList = new ArrayList<Subentry>();
			Set<Subentry> fines = new TreeSet<Subentry>(
					new Comparator<Subentry>() {
						@Override
						public int compare(Subentry subFirst, Subentry subSecond) {
							// TODO Auto-generated method stub
							return subFirst.getSubentryCode().compareTo(
									subSecond.getSubentryCode());
						}
					});
			//合同段对应的抽查项目
			Map<String, List<Subentry>> supMap = new HashMap<String, List<Subentry>>();
			for (SignUpContract conSign : conSignList) {
				//查询 一个合同段下的所有分项
				List<Subentry> subentrys = projquacheckManager
						.findByHqlSignProj(conSign.getId());
				//
				if (null != subentrys) {
					//遍历合同段下的分项
					for (int i = 0; i < subentrys.size(); i++) {
						Subentry oldsub = subentrys.get(i);
						Subentry singoldsub = new Subentry();
						
						try {
							BeanUtils.copyProperties(singoldsub, oldsub);
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						// 合计工程下的所有分项
//						如果工程下的分项重复,将分项抽查数量累加,
//						否则添加到工程分项集合中
						if (fineList.contains(oldsub)) {
							for (int j = 0; j < fineList.size(); j++) {
								Subentry newsub = fineList.get(j);
								//如果为相同的抽查项目,抽查数相加
								if (oldsub.equals(newsub)) {
									newsub.setCheckTotal(MathsUtils.sum(
											oldsub.getCheckTotal(),
											newsub.getCheckTotal()));
									newsub.setQualifiedTotal(MathsUtils.sum(
											oldsub.getQualifiedTotal(),
											newsub.getQualifiedTotal()));
								}
							}
						} else {
							//如果没有,添加到工程下 的抽查项目中
							fineList.add(oldsub);
						}

						// 分项按合同段分类

						// 合同段Id
						String signProjId = singoldsub.getBranch().getUnitProj()
								.getSignQuaCheck().getId();
						if (supMap.keySet().contains(signProjId)) {

							for (String keyV : supMap.keySet()) {
								if (keyV.equals(signProjId)) {
									List<Subentry> signSub = supMap
											.get(signProjId);
									signSub.add(singoldsub);
									supMap.put(signProjId, signSub);
								}
							}
						} else {
							List<Subentry> signSub = new ArrayList<Subentry>();
							signSub.add(singoldsub);
							supMap.put(signProjId, signSub);
						}
					}
				}
			}

			// 加入TreeSet中按单位工程编码排序
			for (Subentry subentry : fineList) {
				fines.add(subentry);
			}

			// 工程下所有分项
			Struts2Utils.getRequest().setAttribute("subentryList", fines);
			// 合同段下的所有分项
			Struts2Utils.getRequest().setAttribute("supMap", supMap);
			return "show";
		}

		return null;
	}

	public String exportword() {
		fingProjSign();
		return "export";
	}

	public String delete() {

		projquacheckManager.deleteSignproj(id);
		try {
			Struts2Utils.sendRedirectUrl(Struts2Utils.getRequest().getHeader(
					"Referer"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return NONE;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Autowired
	public void setProjquacheckManager(ProjquacheckManager projquacheckManager) {
		this.projquacheckManager = projquacheckManager;
	}

	@Autowired
	public void setProjectManager(ProjectManager projectManager) {
		this.projectManager = projectManager;
	}

	public String[] getEntryIdArr() {
		return entryIdArr;
	}

	public void setEntryIdArr(String[] entryIdArr) {
		this.entryIdArr = entryIdArr;
	}

	public List<SignGradeVO> getSignGrades() {
		return signGrades;
	}

	public void setSignGrades(List<SignGradeVO> signGrades) {
		this.signGrades = signGrades;
	}

}
